﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

using AjaxControlToolkit;
using UNDP_Projects.Data_Access;

//Used to send an email address
using System.Net;
using System.Net.Mail;
using System.Security.Cryptography.X509Certificates;
using System.Net.Security;
using System.Drawing;

namespace UNDP_Projects.Project
{
    public partial class ProjectReport : System.Web.UI.Page
    {

        protected void Page_PreInit(object sender, EventArgs e)
        {
            /*if (User.IsInRole("Project"))
            {
                MasterPageFile = "~/MasterPages/Project.Master";
            }
            if (User.IsInRole("Programme"))
            {
                MasterPageFile = "~/MasterPages/Programme.Master";
            }
            if (User.IsInRole("Administrator"))
            {
                MasterPageFile = "~/MasterPages/CO.Master";
            }
            if (User.IsInRole("Project") && User.IsInRole("Programme"))
            {
                MasterPageFile = "~/MasterPages/ProgProject.Master";
            }*/
        }

        protected void Page_Init(object sender, EventArgs e)
        {
            if (Session["Project"] != null && Session["ReportPeriod"] != null && Session["Year"] != null)
            {
                long proj = (long)Session["Project"];
                long rprt = (long)Session["ReportPeriod"];
                long yr = (long)Session["Year"];

                populateGenderMainstreaming(proj, rprt, yr);
                populateEndYrSummary(proj, rprt, yr);
                populatePartnerships(proj, rprt, yr);
                populateLessons(proj, rprt, yr);
                populateActivityUpdates(proj, rprt, yr);
                populateUpcomingQuarter(proj, rprt, yr);
                populatePeaceAndConflict(proj, rprt, yr);
                populateContextualAnalysis(proj, rprt, yr);
                //populateSubOutcomeText("1.1");
                populateCpdOutputIndicator("1.1.1.1");
                populateCpdOutput(string.Empty);
                populateProjectCommentTextbox(proj, rprt, yr);
                populateCFS(proj, rprt, yr);
                populateListofDonors(proj, rprt, yr);
                PopulateAcronyms(proj);
                //populateCpdStatusList(); changeStatusListColors();
            }
            else
            {
                Response.Redirect("~/Project/Saved_Projects/");
            }
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            //if(String.IsNullOrEmpty(Request.QueryString[""]))
            //{
            //    Response.Redirect("~/Admin/Add_Report.aspx");
            //}

            if (Session["Project"] != null && Session["ReportPeriod"] != null && Session["Year"] != null)
            {
                long proj = (long)Session["Project"];
                long rprt = (long)Session["ReportPeriod"];
                long yr = (long)Session["Year"];

                if (rprt != 4)
                {
                    EndYearProjectSummaryPane.Visible = false;
                }

                using (UNDPEntities db = new UNDPEntities())
                {
                    try
                    {
                        var projectName = (from p in db.projects
                                           where p.project_id == proj
                                           select p.project1).FirstOrDefault();
                        var periodName = (from r in db.report_period
                                          where r.report_period_id == rprt
                                          select r.report_period1).FirstOrDefault();
                        var yearName = (from y in db.years
                                        where y.year_id == yr
                                        select y.year1).FirstOrDefault();

                        ProjectLabel.Text = projectName;
                        YearLabel.Text = periodName;
                        ReportPeriodLabel.Text = yearName;

                        ToolkitScriptManager1.CompositeScript.Scripts.Add(new ScriptReference("~/Scripts/CounterScript.js"));
                        
                        //populateListofDonors(proj, rprt, yr);
                        if (!Page.IsPostBack)
                        {
                            //This allows saving of any changes made to the project authors
                            populateAuthortTextBox(proj, rprt, yr);
                        }
                    }
                    catch (Exception ex)
                    {
                        ErrorLabel.Text = "Database error : " + ex.Message + " : " + ex.StackTrace;
                        ErrorLabel.Visible = true;
                    }
                }              
            }
            else
            {
                Response.Redirect("~/Project/Saved_Projects/");
            }
        }
//============================================================================================================
        protected void SaveDonorButton_Click(object sender, EventArgs e)
        {
            long proj = (long)Session["Project"];
            long rprt = (long)Session["ReportPeriod"];
            long yr = (long)Session["Year"];

            try
            {
                UNDPEntities db = new UNDPEntities();

                project_reports editors = db.project_reports.SingleOrDefault(
                                        pr => pr.project_id == proj &&
                                        pr.year_id == yr &&
                                        pr.report_period_id == rprt);

                string donor = "";
                foreach (ListItem li in DonorListBox.Items)
                {
                    if (li.Selected == true)
                    {
                        donor += li.Text + "-";
                    }
                }
                if (donor != "")
                {
                    editors.donors = donor;
                    db.SaveChanges();
                }
                else
                {
                    ErrorLabel.Text = "Please Choose a Donor";
                    ErrorLabel.Visible = true;
                }

                //=============================+
                //  Add a Log Track Record     |
                //=============================+
                log_track newTrack = db.log_track.SingleOrDefault(
                    lt => lt.project_id == proj &&
                    lt.year_id == yr &&
                    lt.report_period_id == rprt);
                if (newTrack != null)
                {
                    newTrack.log_track1 += DateTime.Now.ToString() + ": list of donors modified by :" + User.Identity.Name + ",";
                    db.SaveChanges();
                }

                populateListofDonors(proj, rprt, yr);

            }
            catch (Exception ex)
            {
                ErrorLabel.Text = "Database error : " + ex.Message + " : " + ex.StackTrace;
                ErrorLabel.Visible = true;
            }
        }
//============================================================================================================
        /*protected void populateCpdStatusList()
        {
            using (UNDPEntities db = new UNDPEntities())
            {
                try
                {
                    var status = (from s in db.indicator_status
                                  select new
                                  {
                                      s.indicator_status_id,
                                      s.indicator_status1
                                  });

                    CpdStatusList.DataSource = status;
                    CpdStatusList.DataValueField = "indicator_status_id";
                    CpdStatusList.DataTextField = "indicator_status1";
                    CpdStatusList.DataBind();  
                }
                catch (Exception ex)
                {
                    ErrorLabel.Text = "Database error : " + ex.Message + " : " + ex.StackTrace;
                    ErrorLabel.Visible = true;
                }
            }
        }

        protected void changeStatusListColors()
        {
            for (int i = 0; i < CpdStatusList.Items.Count; ++i)
            {
                if (CpdStatusList.Items[i].Value == "1")
                {
                    CpdStatusList.Items[i].Attributes.Add("style", "background-color:Red");
                }
                else if (CpdStatusList.Items[i].Value == "2")
                {
                    CpdStatusList.Items[i].Attributes.Add("style", "background-color:Yellow");
                }
                else if (CpdStatusList.Items[i].Value == "3")
                {
                    CpdStatusList.Items[i].Attributes.Add("style", "background-color:Green");
                }
            }
            CpdStatusList.BackColor = System.Drawing.Color.FromName(CpdStatusList.SelectedItem.Text);
        }

        protected void CpdStatusList_OnSelectedIndexChanged(object sender, EventArgs e)
        {
            CpdStatusList.BackColor = System.Drawing.Color.FromName(CpdStatusList.SelectedItem.Text);
            changeStatusListColors();
        }*/
//============================================================================================================
        protected void populateListofDonors(long dproj, long drprt, long dyr)
        {
            using (UNDPEntities db = new UNDPEntities())
            {
                try
                {
                    var donors = (from d in db.project_reports
                                  where d.project_id == dproj &&
                                  d.year_id == dyr && d.report_period_id == drprt
                                  select d.donors).FirstOrDefault();

                    char[] separator = new char[] { '-' };
                    string[] donorList = donors.Split(separator);

                    ProjectDataPane.FindControl("DonorsListBox");

                    DonorsListBox.DataSource = donorList;
                    DonorsListBox.DataBind();
                }
                catch (Exception ex)
                {
                    ErrorLabel.Text = "Database error : " + ex.Message + " : " + ex.StackTrace;
                    ErrorLabel.Visible = true;
                }
            }
        }
//============================================================================================================
        protected void EditorButton_Click(object sender, EventArgs e)
        {
            long proj = (long)Session["Project"];
            long rprt = (long)Session["ReportPeriod"];
            long yr = (long)Session["Year"];

            try
            {
                UNDPEntities db = new UNDPEntities();

                project_reports editors = db.project_reports.SingleOrDefault(
                                        pr => pr.project_id == proj && 
                                        pr.year_id == yr && 
                                        pr.report_period_id == rprt);

                if (AuthorTextBox.Text == String.Empty)
                {
                    Label40.Text = "*Please enter all contributers";
                    Label40.ForeColor = System.Drawing.Color.Red;
                }

                if (editors != null)
                {
                    editors.project_editor = AuthorTextBox.Text;
                    db.SaveChanges();
                }

                //=============================+
                //  Add a Log Track Record     |
                //=============================+
                log_track newTrack = db.log_track.SingleOrDefault(
                    lt => lt.project_id == proj && 
                    lt.year_id == yr && 
                    lt.report_period_id == rprt);
                if (newTrack != null)
                {
                    newTrack.log_track1 += DateTime.Now.ToString() + ": list of contributers modified by :" + User.Identity.Name + ",";
                    db.SaveChanges();
                }

            }
            catch (Exception ex)
            {
                ErrorLabel.Text = "Database error : " + ex.Message + " : " + ex.StackTrace;
                ErrorLabel.Visible = true;
            }
        }
//============================================================================================================
        protected void populateAuthortTextBox(long aproj, long arprt, long ayr)
        {
            using (UNDPEntities db = new UNDPEntities())
            {
                try
                {
                    var author = (from a in db.project_reports 
                                      where a.project_id == aproj && 
                                      a.year_id == ayr && a.report_period_id == arprt 
                                      select a.project_editor).FirstOrDefault();

                    AuthorTextBox.Text = author;
                }
                catch (Exception ex)
                {
                    ErrorLabel.Text = "Database error : " + ex.Message + " : " + ex.StackTrace;
                    ErrorLabel.Visible = true;
                }
            }
        }
//============================================================================================================
        protected void populateEndYrSummary(long projectID, long reportPeriodID, long yearID)
        {
            using (UNDPEntities db = new UNDPEntities())
            {
                try
                {
                    var summary = (from data in db.project_reports
                                   where
                                       data.project_id == projectID &&
                                       data.report_period_id == reportPeriodID &&
                                       data.year_id == yearID
                                   select data.end_year_summary).FirstOrDefault();

                    EndYearProjectSummaryPane.FindControl("EndYrSummaryTextBox");
                    EndYrSummaryTextBox.Text = summary;
                }
                catch (Exception ex)
                {
                    ErrorLabel.Text = "Database error : " + ex.Message + " : " + ex.StackTrace;
                    ErrorLabel.Visible = true;
                }
            }
        }
//============================================================================================================
        protected void EndYrSummaryButton_Click(object sender, EventArgs e)
        {
            long proj = (long)Session["Project"];
            long rprt = (long)Session["ReportPeriod"];
            long yr = (long)Session["Year"];
            try
            {
                UNDPEntities db = new UNDPEntities();
                project_reports summary = db.project_reports.SingleOrDefault(
                    data => data.project_id == proj
                    && data.report_period_id == rprt
                    && data.year_id == yr);

                if (summary != null)
                {
                    summary.end_year_summary = EndYrSummaryTextBox.Text.Trim();
                    db.SaveChanges();
                }
                else if (summary == null)
                {
                    Response.Redirect("~/Project/Saved_Projects/");
                }
            }
            catch (Exception ex)
            {
                ErrorLabel.Text = "Database error : " + ex.Message + " : " + ex.StackTrace;
                ErrorLabel.Visible = true;
            }
            populateEndYrSummary(proj, rprt, yr);
        }
//============================================================================================================
        protected void populateGenderMainstreaming(long gproj, long grprt, long gyr)
        {
            using (UNDPEntities db = new UNDPEntities())
            {
                try
                {
                    var gender = (from pr in db.project_reports
                                    where pr.project_id == gproj &&
                                    pr.year_id == gyr && pr.report_period_id == grprt
                                    select pr.gender_mainstreaming).FirstOrDefault();
                    
                    GenderMainstreamPane.FindControl("GenderMainstreamingTextBox");
                    GenderMainstreamingTextBox.Text = gender;
                }
                catch (Exception ex)
                {
                    ErrorLabel.Text = "Database error : " + ex.Message + " : " + ex.StackTrace;
                    ErrorLabel.Visible = true;
                }
            }
        }
//============================================================================================================
        //WORKING PERFECTLY
        protected void GenderButton_Click(object sender, EventArgs e)
        {
            long proj = (long)Session["Project"];
            long rprt = (long)Session["ReportPeriod"];
            long yr = (long)Session["Year"];
            try
            {     
                UNDPEntities db = new UNDPEntities();
                project_reports gender = db.project_reports.SingleOrDefault(
                                            pr => pr.project_id == proj && 
                                            pr.year_id == yr && 
                                            pr.report_period_id == rprt);
                if (gender != null)
                {
                    gender.gender_mainstreaming = GenderMainstreamingTextBox.Text;
                    db.SaveChanges();
                }
                else if (gender == null)
                {
                    Response.Redirect("~/Project/Saved_Projects/");
                }

                //=============================+
                //  Add a Log Track Record     |
                //=============================+
                log_track newTrack = db.log_track.SingleOrDefault(
                    lt => lt.project_id == proj &&
                    lt.year_id == yr &&
                    lt.report_period_id == rprt);
                if (newTrack != null)
                {
                    newTrack.log_track1 += DateTime.Now.ToString() + ": Gender modified by :" + User.Identity.Name + ",";
                    db.SaveChanges();
                }

            }
            catch (Exception ex)
            {
                ErrorLabel.Text = "Database error : " + ex.Message + " : " + ex.StackTrace;
                ErrorLabel.Visible = true;
            }
            populateGenderMainstreaming(proj, rprt, yr);
        }
//==============================================================================================================
        protected void populatePartnerships(long pproj, long prprt, long pyr)
        {
            using (UNDPEntities db = new UNDPEntities())
            {
                try
                {
                    var partnerships = (from pr in db.project_reports
                                  where pr.project_id == pproj &&
                                  pr.year_id == pyr && pr.report_period_id == prprt
                                  select pr.partnerships).FirstOrDefault();

                    PartnershipsPane.FindControl("PartnershipsTextBox");
                    PartnershipsTextBox.Text = partnerships;
                }
                catch (Exception ex)
                {
                    ErrorLabel.Text = "Database error : " + ex.Message + " : " + ex.StackTrace;
                    ErrorLabel.Visible = true;
                }
            }
        }
//===============================================================================================================
        protected void PartnershipButton_Click(object sender, EventArgs e)
        {
            long proj = (long)Session["Project"];
            long rprt = (long)Session["ReportPeriod"];
            long yr = (long)Session["Year"];
            try
            {
                UNDPEntities db = new UNDPEntities();
                project_reports p = db.project_reports.SingleOrDefault(
                                            pr => pr.project_id == proj &&
                                            pr.year_id == yr &&
                                            pr.report_period_id == rprt);
                if (p != null)
                {
                    p.partnerships = PartnershipsTextBox.Text;
                    db.SaveChanges();
                }
                else if (p == null)
                {
                    Response.Redirect("~/Project/Saved_Projects/");
                }

                //=============================+
                //  Add a Log Track Record     |
                //=============================+
                log_track newTrack = db.log_track.SingleOrDefault(
                    lt => lt.project_id == proj &&
                    lt.year_id == yr &&
                    lt.report_period_id == rprt);
                if (newTrack != null)
                {
                    newTrack.log_track1 += DateTime.Now.ToString() + ": Partnerships modified by :" + User.Identity.Name + ",";
                    db.SaveChanges();
                }

            }
            catch (Exception ex)
            {
                ErrorLabel.Text = "Database error : " + ex.Message + " : " + ex.StackTrace;
                ErrorLabel.Visible = true;
            }
            populatePartnerships(proj, rprt, yr);
        }
//===============================================================================================================
        protected void populateLessons(long lproj, long lrprt, long lyr)
        {
            using (UNDPEntities db = new UNDPEntities())
            {
                try
                {
                    var lessons = (from pr in db.project_reports
                                        where pr.project_id == lproj &&
                                        pr.year_id == lyr && pr.report_period_id == lrprt
                                        select pr.lessons).FirstOrDefault();

                    LessonsPane.FindControl("LessonsTextBox");
                    LessonsTextBox.Text = lessons;
                }
                catch (Exception ex)
                {
                    ErrorLabel.Text = "Database error : " + ex.Message + " : " + ex.StackTrace;
                    ErrorLabel.Visible = true;
                }
            }
        }
//===============================================================================================================
        protected void LessonButton_Click(object sender, EventArgs e)
        {
            long proj = (long)Session["Project"];
            long rprt = (long)Session["ReportPeriod"];
            long yr = (long)Session["Year"];
            try
            {
                UNDPEntities db = new UNDPEntities();
                project_reports l = db.project_reports.SingleOrDefault(
                                            pr => pr.project_id == proj &&
                                            pr.year_id == yr &&
                                            pr.report_period_id == rprt);
                if (l != null)
                {
                    l.lessons = LessonsTextBox.Text;
                    db.SaveChanges();
                }
                else if (l == null)
                {
                    Response.Redirect("~/Project/Saved_Projects/");
                }

                //=============================+
                //  Add a Log Track Record     |
                //=============================+
                log_track newTrack = db.log_track.SingleOrDefault(
                    lt => lt.project_id == proj &&
                    lt.year_id == yr &&
                    lt.report_period_id == rprt);
                if (newTrack != null)
                {
                    newTrack.log_track1 += DateTime.Now.ToString() + ": Reflections/Lessons modified by :" + User.Identity.Name + ",";
                    db.SaveChanges();
                }

            }
            catch (Exception ex)
            {
                ErrorLabel.Text = "Database error : " + ex.Message + " : " + ex.StackTrace;
                ErrorLabel.Visible = true;
            }
            populateLessons(proj, rprt, yr);
        }
//===============================================================================================================
        protected void populateActivityUpdates(long aproj, long arprt, long ayr)
        {
            using (UNDPEntities db = new UNDPEntities())
            {
                try
                {
                    long SLreg = 1;
                    long PLreg = 2;
                    long SCreg = 3;

                    var SLactivity = (from pr in db.activity_updates
                                   where pr.project_id == aproj &&
                                   pr.year_id == ayr && pr.report_period_id == arprt && 
                                   pr.region_id == SLreg
                                   select pr.activity_update).FirstOrDefault();

                    var PLactivity = (from pr in db.activity_updates
                                      where pr.project_id == aproj &&
                                      pr.year_id == ayr && pr.report_period_id == arprt &&
                                      pr.region_id == PLreg
                                      select pr.activity_update).FirstOrDefault();

                    var SCactivity = (from pr in db.activity_updates
                                      where pr.project_id == aproj &&
                                      pr.year_id == ayr && pr.report_period_id == arprt &&
                                      pr.region_id == SCreg
                                      select pr.activity_update).FirstOrDefault();

                    if (SLactivity == null)
                    {
                        //Important...Used at the Page_Init stage above
                        ActivityPane.FindControl("SLActivityTextBox");
                        SLActivityTextBox.Text = null;
                    }
                    else
                    {
                        ActivityPane.FindControl("SLActivityTextBox");
                        SLActivityTextBox.Text = SLactivity;
                    }

                    if (PLactivity == null)
                    {
                        //Important...Used at the Page_Init stage above
                        ActivityPane.FindControl("PLActivityTextbox");
                        PLActivityTextbox.Text = null;
                    }
                    else
                    {
                        ActivityPane.FindControl("PLActivityTextbox");
                        PLActivityTextbox.Text = PLactivity;
                    }

                    if (SCactivity == null)
                    {
                        //Important...Used at the Page_Init stage above
                        ActivityPane.FindControl("SCActivityTextbox");
                        SCActivityTextbox.Text = null;
                    }
                    else
                    {
                        ActivityPane.FindControl("SCActivityTextbox");
                        SCActivityTextbox.Text = SCactivity;
                    }
                }
                catch (Exception ex)
                {
                    ErrorLabel.Text = "Database error : " + ex.Message + " : " + ex.StackTrace;
                    ErrorLabel.Visible = true;
                }
            }
        }
//===============================================================================================================
        protected void SLActivityButton_Click(object sender, EventArgs e)
        {
            long proj = (long)Session["Project"];
            long rprt = (long)Session["ReportPeriod"];
            long yr = (long)Session["Year"];
            long reg = 1;

            using (UNDPEntities db = new UNDPEntities())
            {
                try
                {
                    var ac_up = (from au in db.activity_updates
                                 where
                                     au.project_id == proj &&
                                     au.year_id == yr &&
                                     au.report_period_id == rprt &&
                                     au.region_id == reg
                                 select au.activity_update).FirstOrDefault();

                    if (ac_up == null)
                    {
                        //=======================================+
                        //  Add a new Activity_Update Record     |
                        //=======================================+
                        activity_updates newAU = new activity_updates();
                        newAU.project_id = proj;
                        newAU.year_id = yr;
                        newAU.report_period_id = rprt;
                        newAU.region_id = reg;
                        newAU.activity_update = SLActivityTextBox.Text;

                        db.activity_updates.AddObject(newAU);
                        db.SaveChanges();
                    }
                    else if (ac_up != null)
                    {
                        //========================================+
                        //  UPDATE the Activity_Update Record     |
                        //========================================+
                        activity_updates au = db.activity_updates.SingleOrDefault(
                                                au_1 => au_1.project_id == proj &&
                                                au_1.year_id == yr &&
                                                au_1.report_period_id == rprt &&
                                                au_1.region_id == reg);

                        au.activity_update = SLActivityTextBox.Text;
                        db.SaveChanges();
                    }

                    //=============================+
                    //  Add a Log Track Record     |
                    //=============================+
                    log_track newTrack = db.log_track.SingleOrDefault(
                        lt => lt.project_id == proj &&
                        lt.year_id == yr &&
                        lt.report_period_id == rprt);
                    if (newTrack != null)
                    {
                        newTrack.log_track1 += DateTime.Now.ToString() + ": SL Activity Highlights modified by :" + User.Identity.Name + ",";
                        db.SaveChanges();
                    }

                }
                catch (Exception ex)
                {
                    ErrorLabel.Text = "Error : " + ex.Message + " : " + ex.StackTrace;
                    ErrorLabel.Visible = true;
                }
            }
            populateActivityUpdates(proj, rprt, yr);
        }
//===============================================================================================================
        protected void PLActivityButton_Click(object sender, EventArgs e)
        {
            long proj = (long)Session["Project"];
            long rprt = (long)Session["ReportPeriod"];
            long yr = (long)Session["Year"];
            long reg = 2;

            using (UNDPEntities db = new UNDPEntities())
            {
                try
                {
                    var ac_up = (from au in db.activity_updates
                                 where
                                     au.project_id == proj &&
                                     au.year_id == yr &&
                                     au.report_period_id == rprt &&
                                     au.region_id == reg
                                 select au.activity_update).FirstOrDefault();

                    if (ac_up == null)
                    {
                        //=======================================+
                        //  Add a new Activity_Update Record     |
                        //=======================================+
                        activity_updates newAU = new activity_updates();
                        newAU.project_id = proj;
                        newAU.year_id = yr;
                        newAU.report_period_id = rprt;
                        newAU.region_id = reg;
                        newAU.activity_update = PLActivityTextbox.Text;

                        db.activity_updates.AddObject(newAU);
                        db.SaveChanges();
                    }
                    else if (ac_up != null)
                    {
                        //========================================+
                        //  UPDATE the Activity_Update Record     |
                        //========================================+
                        activity_updates au = db.activity_updates.SingleOrDefault(
                                                au_1 => au_1.project_id == proj &&
                                                au_1.year_id == yr &&
                                                au_1.report_period_id == rprt &&
                                                au_1.region_id == reg);

                        au.activity_update = PLActivityTextbox.Text;
                        db.SaveChanges();
                    }

                    //=============================+
                    //  Add a Log Track Record     |
                    //=============================+
                    log_track newTrack = db.log_track.SingleOrDefault(
                        lt => lt.project_id == proj &&
                        lt.year_id == yr &&
                        lt.report_period_id == rprt);
                    if (newTrack != null)
                    {
                        newTrack.log_track1 += DateTime.Now.ToString() + ": PL Activity Highlights modified by :" + User.Identity.Name + ",";
                        db.SaveChanges();
                    }

                }
                catch (Exception ex)
                {
                    ErrorLabel.Text = "Error : " + ex.Message + " : " + ex.StackTrace;
                    ErrorLabel.Visible = true;
                }
            }
            populateActivityUpdates(proj, rprt, yr);
        }
//===============================================================================================================
        protected void SCActivityButton_Click(object sender, EventArgs e)
        {
            long proj = (long)Session["Project"];
            long rprt = (long)Session["ReportPeriod"];
            long yr = (long)Session["Year"];
            long reg = 3;

            using (UNDPEntities db = new UNDPEntities())
            {
                try
                {
                    var ac_up = (from au in db.activity_updates
                                 where
                                     au.project_id == proj &&
                                     au.year_id == yr &&
                                     au.report_period_id == rprt &&
                                     au.region_id == reg
                                 select au.activity_update).FirstOrDefault();

                    if (ac_up == null)
                    {
                        //=======================================+
                        //  Add a new Activity_Update Record     |
                        //=======================================+
                        activity_updates newAU = new activity_updates();
                        newAU.project_id = proj;
                        newAU.year_id = yr;
                        newAU.report_period_id = rprt;
                        newAU.region_id = reg;
                        newAU.activity_update = SCActivityTextbox.Text;

                        db.activity_updates.AddObject(newAU);
                        db.SaveChanges();
                    }
                    else if (ac_up != null)
                    {
                        //========================================+
                        //  UPDATE the Activity_Update Record     |
                        //========================================+
                        activity_updates au = db.activity_updates.SingleOrDefault(
                                                au_1 => au_1.project_id == proj &&
                                                au_1.year_id == yr &&
                                                au_1.report_period_id == rprt &&
                                                au_1.region_id == reg);

                        au.activity_update = SCActivityTextbox.Text;
                        db.SaveChanges();
                    }

                    //=============================+
                    //  Add a Log Track Record     |
                    //=============================+
                    log_track newTrack = db.log_track.SingleOrDefault(
                        lt => lt.project_id == proj &&
                        lt.year_id == yr &&
                        lt.report_period_id == rprt);
                    if (newTrack != null)
                    {
                        newTrack.log_track1 += DateTime.Now.ToString() + ": SC Activity Highlights modified by :" + User.Identity.Name + ",";
                        db.SaveChanges();
                    }

                }
                catch (Exception ex)
                {
                    ErrorLabel.Text = "Error : " + ex.Message + " : " + ex.StackTrace;
                    ErrorLabel.Visible = true;
                }
            }
            populateActivityUpdates(proj, rprt, yr);
        }
//===============================================================================================================
        protected void populateUpcomingQuarter(long qproj, long qrprt, long qyr)
        {
            using (UNDPEntities db = new UNDPEntities())
            {
                try
                {
                    var uQuarter = (from pr in db.project_reports
                                    where pr.project_id == qproj &&
                                    pr.year_id == qyr && pr.report_period_id == qrprt
                                    select pr.upcoming_quarter).FirstOrDefault();

                    UpcomingQuarterPane.FindControl("UpcomingQuarterTextBox");
                    UpcomingQuarterTextBox.Text = uQuarter;
                }
                catch (Exception ex)
                {
                    ErrorLabel.Text = "Database error : " + ex.Message + " : " + ex.StackTrace;
                    ErrorLabel.Visible = true;
                }
            }
        }
//===============================================================================================================
        protected void QuarterButton_Click(object sender, EventArgs e)
        {
            long proj = (long)Session["Project"];
            long rprt = (long)Session["ReportPeriod"];
            long yr = (long)Session["Year"];
            try
            {
                UNDPEntities db = new UNDPEntities();
                project_reports uq = db.project_reports.SingleOrDefault(
                                            pr => pr.project_id == proj &&
                                            pr.year_id == yr &&
                                            pr.report_period_id == rprt);
                if (uq != null)
                {
                    uq.upcoming_quarter = UpcomingQuarterTextBox.Text;
                    db.SaveChanges();
                }
                else if (uq == null)
                {
                    Response.Redirect("~/Project/Saved_Projects/");
                }

                //=============================+
                //  Add a Log Track Record     |
                //=============================+
                log_track newTrack = db.log_track.SingleOrDefault(
                    lt => lt.project_id == proj &&
                    lt.year_id == yr &&
                    lt.report_period_id == rprt);
                if (newTrack != null)
                {
                    newTrack.log_track1 += DateTime.Now.ToString() + ": Upcoming Quarter modified by :" + User.Identity.Name + ",";
                    db.SaveChanges();
                }

            }
            catch (Exception ex)
            {
                ErrorLabel.Text = "Database error : " + ex.Message + " : " + ex.StackTrace;
                ErrorLabel.Visible = true;
            }
            populateUpcomingQuarter(proj, rprt, yr);
        }
//==============================================================================================================
        protected void populatePeaceAndConflict(long pcproj, long pcrprt, long pcyr)
        {
            using (UNDPEntities db = new UNDPEntities())
            {
                try
                {
                    var peaceConflict = (from pr in db.project_reports
                                    where pr.project_id == pcproj &&
                                    pr.year_id == pcyr && pr.report_period_id == pcrprt
                                    select pr.peace_and_conflict).FirstOrDefault();
                    
                    PeaceConflictPane.FindControl("PeaceConflictTextBox");
                    PeaceConflictTextBox.Text = peaceConflict;
                }
                catch (Exception ex)
                {
                    ErrorLabel.Text = "Database error : " + ex.Message + " : " + ex.StackTrace;
                    ErrorLabel.Visible = true;
                }
            }
        }
//===============================================================================================================
        protected void PeaceButton_Click(object sender, EventArgs e)
        {
            long proj = (long)Session["Project"];
            long rprt = (long)Session["ReportPeriod"];
            long yr = (long)Session["Year"];
            try
            {
                UNDPEntities db = new UNDPEntities();
                project_reports pc = db.project_reports.SingleOrDefault(
                                            pr => pr.project_id == proj &&
                                            pr.year_id == yr &&
                                            pr.report_period_id == rprt);
                if (pc != null)
                {
                    pc.peace_and_conflict = PeaceConflictTextBox.Text;
                    db.SaveChanges();
                }
                else if (pc == null)
                {
                    Response.Redirect("~/Project/Saved_Projects/");
                }

                //=============================+
                //  Add a Log Track Record     |
                //=============================+
                log_track newTrack = db.log_track.SingleOrDefault(
                    lt => lt.project_id == proj &&
                    lt.year_id == yr &&
                    lt.report_period_id == rprt);
                if (newTrack != null)
                {
                    newTrack.log_track1 += DateTime.Now.ToString() + ": Peace and Conflict modified by :" + User.Identity.Name + ",";
                    db.SaveChanges();
                }

            }
            catch (Exception ex)
            {
                ErrorLabel.Text = "Database error : " + ex.Message + " : " + ex.StackTrace;
                ErrorLabel.Visible = true;
            }
            populatePeaceAndConflict(proj, rprt, yr);
        }
//===============================================================================================================
        protected void populateContextualAnalysis(long pcproj, long pcrprt, long pcyr)
        {
            using (UNDPEntities db = new UNDPEntities())
            {
                try
                {
                    long SLreg = 1;
                    long PLreg = 2;
                    long SCreg = 3;

                    var caslContent = (from casl in db.contextual_analysis 
                                       where casl.project_id == pcproj && 
                                       casl.year_id == pcyr && casl.report_period_id == pcrprt 
                                       && casl.region_id == SLreg 
                                       select casl.contextual_analysis1).FirstOrDefault();

                    var caplContent = (from capl in db.contextual_analysis
                                        where capl.project_id == pcproj &&
                                        capl.year_id == pcyr && capl.report_period_id == pcrprt
                                        && capl.region_id == PLreg
                                        select capl.contextual_analysis1).FirstOrDefault();

                    var cascContent = (from casc in db.contextual_analysis
                                        where casc.project_id == pcproj &&
                                        casc.year_id == pcyr && casc.report_period_id == pcrprt
                                        && casc.region_id == SCreg
                                        select casc.contextual_analysis1).FirstOrDefault();

                    if (caslContent == null)
                    {
                        //Important...Used at the Page_Init stage above
                        ContextualAnalysisPane.FindControl("SLCATextBox");
                        SLCATextBox.Text = null;
                    }
                    else
                    {
                        ContextualAnalysisPane.FindControl("SLCATextBox");
                        SLCATextBox.Text = caslContent;
                    }

                    if (caplContent == null)
                    {
                        //Important...Used at the Page_Init stage above
                        ContextualAnalysisPane.FindControl("PLCATextBox");
                        PLCATextBox.Text = null;
                    }
                    else
                    {
                        ContextualAnalysisPane.FindControl("PLCATextBox");
                        PLCATextBox.Text = caplContent;
                    }

                    if (cascContent == null)
                    {
                        //Important...Used at the Page_Init stage above
                        ContextualAnalysisPane.FindControl("SCCATextBox");
                        SCCATextBox.Text = null;
                    }
                    else
                    {
                        ContextualAnalysisPane.FindControl("SCCATextBox");
                        SCCATextBox.Text = cascContent;
                    }
                }
                catch (Exception ex)
                {
                    ErrorLabel.Text = "Database error : " + ex.Message + " : " + ex.StackTrace;
                    ErrorLabel.Visible = true;
                }
            }
        }
//===============================================================================================================
        protected void SLCAButton_Click(object sender, EventArgs e)
        {
            long proj = (long)Session["Project"];
            long rprt = (long)Session["ReportPeriod"];
            long yr = (long)Session["Year"];
            long reg = 1;

            using (UNDPEntities db = new UNDPEntities())
            {
                try
                {
                    var c = (from ca in db.contextual_analysis
                             where ca.project_id == proj &&
                             ca.year_id == yr && ca.report_period_id == rprt
                             && ca.region_id == reg
                             select ca.contextual_analysis1).FirstOrDefault();

                    if (c == null)
                    {
                        //===========================================+
                        //  Add a new Contextual_Analysis Record     |
                        //===========================================+
                        contextual_analysis newCA = new contextual_analysis();
                        newCA.project_id = proj;
                        newCA.year_id = yr;
                        newCA.report_period_id = rprt;
                        newCA.region_id = reg;
                        newCA.contextual_analysis1 = SLCATextBox.Text;

                        db.contextual_analysis.AddObject(newCA);
                        db.SaveChanges();
                    }
                    else if (c != null)
                    {
                        //============================================+
                        //  UPDATE the Contextual_Analysis Record     |
                        //============================================+
                        contextual_analysis ca = db.contextual_analysis.SingleOrDefault(
                                                    ca_1 => ca_1.project_id == proj &&
                                                    ca_1.year_id == yr &&
                                                    ca_1.report_period_id == rprt &&
                                                    ca_1.region_id == reg);

                        ca.contextual_analysis1 = SLCATextBox.Text;
                        db.SaveChanges();
                    }

                    //=============================+
                    //  Add a Log Track Record     |
                    //=============================+
                    log_track newTrack = db.log_track.SingleOrDefault(
                        lt => lt.project_id == proj &&
                        lt.year_id == yr &&
                        lt.report_period_id == rprt);
                    if (newTrack != null)
                    {
                        newTrack.log_track1 += DateTime.Now.ToString() + ": SL Contextual Analysis modified by :" + User.Identity.Name + ",";
                        db.SaveChanges();
                    }

                }
                catch (Exception ex)
                {
                    ErrorLabel.Text = "Database error : " + ex.Message + " : " + ex.StackTrace;
                    ErrorLabel.Visible = true;
                }
            }
            populateContextualAnalysis(proj, rprt, yr);
        }
//===============================================================================================================
        protected void PLCAButton_Click(object sender, EventArgs e)
        {
            long proj = (long)Session["Project"];
            long rprt = (long)Session["ReportPeriod"];
            long yr = (long)Session["Year"];
            long reg = 2;

            using (UNDPEntities db = new UNDPEntities())
            {
                try
                {
                    var c = (from ca in db.contextual_analysis
                             where ca.project_id == proj &&
                             ca.year_id == yr && ca.report_period_id == rprt
                             && ca.region_id == reg
                             select ca.contextual_analysis1).FirstOrDefault();

                    if (c == null)
                    {
                        //===========================================+
                        //  Add a new Contextual_Analysis Record     |
                        //===========================================+
                        contextual_analysis newCA = new contextual_analysis();
                        newCA.project_id = proj;
                        newCA.year_id = yr;
                        newCA.report_period_id = rprt;
                        newCA.region_id = reg;
                        newCA.contextual_analysis1 = PLCATextBox.Text;

                        db.contextual_analysis.AddObject(newCA);
                        db.SaveChanges();
                    }
                    else if (c != null)
                    {
                        //============================================+
                        //  UPDATE the Contextual_Analysis Record     |
                        //============================================+
                        contextual_analysis ca = db.contextual_analysis.SingleOrDefault(
                                                    ca_1 => ca_1.project_id == proj &&
                                                    ca_1.year_id == yr &&
                                                    ca_1.report_period_id == rprt &&
                                                    ca_1.region_id == reg);

                        ca.contextual_analysis1 = PLCATextBox.Text;
                        db.SaveChanges();
                    }

                    //=============================+
                    //  Add a Log Track Record     |
                    //=============================+
                    log_track newTrack = db.log_track.SingleOrDefault(
                        lt => lt.project_id == proj &&
                        lt.year_id == yr &&
                        lt.report_period_id == rprt);
                    if (newTrack != null)
                    {
                        newTrack.log_track1 += DateTime.Now.ToString() + ": PL Contextual Analysis modified by :" + User.Identity.Name + ",";
                        db.SaveChanges();
                    }

                }
                catch (Exception ex)
                {
                    ErrorLabel.Text = "Database error : " + ex.Message + " : " + ex.StackTrace;
                    ErrorLabel.Visible = true;
                }
            }
            populateContextualAnalysis(proj, rprt, yr);
        }
//===============================================================================================================
        protected void SCCAButton_Click(object sender, EventArgs e)
        {
            long proj = (long)Session["Project"];
            long rprt = (long)Session["ReportPeriod"];
            long yr = (long)Session["Year"];
            long reg = 3;

            using (UNDPEntities db = new UNDPEntities())
            {
                try
                {
                    var c = (from ca in db.contextual_analysis
                             where ca.project_id == proj &&
                             ca.year_id == yr && ca.report_period_id == rprt
                             && ca.region_id == reg
                             select ca.contextual_analysis1).FirstOrDefault();

                    if (c == null)
                    {
                        //===========================================+
                        //  Add a new Contextual_Analysis Record     |
                        //===========================================+
                        contextual_analysis newCA = new contextual_analysis();
                        newCA.project_id = proj;
                        newCA.year_id = yr;
                        newCA.report_period_id = rprt;
                        newCA.region_id = reg;
                        newCA.contextual_analysis1 = SCCATextBox.Text;

                        db.contextual_analysis.AddObject(newCA);
                        db.SaveChanges();
                    }
                    else if (c != null)
                    {
                        //============================================+
                        //  UPDATE the Contextual_Analysis Record     |
                        //============================================+
                        contextual_analysis ca = db.contextual_analysis.SingleOrDefault(
                                                    ca_1 => ca_1.project_id == proj &&
                                                    ca_1.year_id == yr &&
                                                    ca_1.report_period_id == rprt &&
                                                    ca_1.region_id == reg);

                        ca.contextual_analysis1 = SCCATextBox.Text;
                        db.SaveChanges();
                    }

                    //=============================+
                    //  Add a Log Track Record     |
                    //=============================+
                    log_track newTrack = db.log_track.SingleOrDefault(
                        lt => lt.project_id == proj &&
                        lt.year_id == yr &&
                        lt.report_period_id == rprt);
                    if (newTrack != null)
                    {
                        newTrack.log_track1 += DateTime.Now.ToString() + ": SC contextual Analysis modified by :" + User.Identity.Name + ",";
                        db.SaveChanges();
                    }

                }
                catch (Exception ex)
                {
                    ErrorLabel.Text = "Database error : " + ex.Message + " : " + ex.StackTrace;
                    ErrorLabel.Visible = true;
                }
            }
            populateContextualAnalysis(proj, rprt, yr);
        }
//===============================================================================================================
        /*protected void populateSubOutcomeText(string subOutcomeID)
        {
            using (UNDPEntities db = new UNDPEntities())
            {
                try
                {
                    var subOutcome = (from s in db.sub_outcomes
                                      where s.sub_outcome_id == subOutcomeID
                                      select s.sub_outcome).FirstOrDefault();

                    if (subOutcome == null)
                    {
                        //Important...Used at the Page_Init stage above
                        SubOutcomePane.FindControl("SubOutcomeTextBox");
                        SubOutcomeTextBox.Text = null;
                    }
                    else
                    {
                        //Important...Used at the Page_Init stage above
                        SubOutcomePane.FindControl("SubOutcomeTextBox");
                        SubOutcomeTextBox.Text = subOutcome;
                    }
                }
                catch (Exception ex)
                {
                    ErrorLabel.Text = "Database error : " + ex.Message + " : " + ex.StackTrace;
                    ErrorLabel.Visible = true;
                }
            }
        }
//===============================================================================================================
        protected void SubOutcomeList_SelectedIndexChanged(object sender, EventArgs e)
        {
            using (UNDPEntities db = new UNDPEntities())
            {
                try
                {
                    var subOutcome = (from s in db.sub_outcomes
                                      where s.sub_outcome_id == SubOutcomeList.SelectedValue
                                      select s.sub_outcome).FirstOrDefault();
                    if (subOutcome == null)
                    {
                        SubOutcomeTextBox.Text = null;
                    }
                    else
                    {
                        SubOutcomeTextBox.Text = subOutcome;
                    }
                }
                catch (Exception ex)
                {
                    ErrorLabel.Text = "Database error : " + ex.Message + " : " + ex.StackTrace;
                    ErrorLabel.Visible = true;
                }
            }
        }
//===============================================================================================================
        protected void clearSubOutcomeSelectors()
        {
            SubOutcomeList.SelectedIndex = 0;
            SubOutcomeResultTextBox.Text = null;
        }
//===============================================================================================================
        protected void SaveSubOutcomeButton_Click(object sender, EventArgs e)
        {
            long proj = (long)Session["Project"];
            long rprt = (long)Session["ReportPeriod"];
            long yr = (long)Session["Year"];
            string subOutcomeID = SubOutcomeList.SelectedValue;

            using (UNDPEntities db = new UNDPEntities())
            {
                try
                {
                    var result = (from data in db.sub_outcome_results
                                  where data.project_id == proj
                                  && data.report_period_id == rprt
                                  && data.year_id == yr
                                  && data.sub_outcome_id == subOutcomeID
                                  select data).FirstOrDefault();//FirstOrDefault() is important as it won't
                                                                //do a selection without it.
                    if (result == null)
                    {
                        //==========================================+
                        //  Add a new Sub Outcome Result Record     |
                        //==========================================+
                        sub_outcome_results newSubOutcome = new sub_outcome_results();
                        newSubOutcome.sub_outcome_id = subOutcomeID;
                        newSubOutcome.project_id = proj;
                        newSubOutcome.year_id = yr;
                        newSubOutcome.report_period_id = rprt;
                        newSubOutcome.result = SubOutcomeResultTextBox.Text;
                        db.sub_outcome_results.AddObject(newSubOutcome);
                        db.SaveChanges();
                    }
                    else if (result != null)
                    {
                        ClientScript.RegisterStartupScript(
                            this.GetType(),
                            "myalert",
                            "alert('That Sub Outcome has already been answered');",
                            true);
                        return;
                    }
                }
                catch (Exception ex)
                {
                    ErrorLabel.Text = "Error : " + ex.Message + " : " + ex.StackTrace;
                    ErrorLabel.Visible = true;
                }
            }
            clearSubOutcomeSelectors();
            populateSubOutcomeText("1.1");
            //Important...
            SubOutcomePane.FindControl("SubOutcomeGridView").DataBind();
        }
//===============================================================================================================
        protected void SubOutcomeGridView_RowUpdating(object sender, GridViewUpdateEventArgs e)
        {
            long proj = (long)Session["Project"];
            long rprt = (long)Session["ReportPeriod"];
            long yr = (long)Session["Year"];

            GridViewRow row = SubOutcomeGridView.Rows[e.RowIndex];

            DropDownList selectedSubOutcome = (DropDownList)row.FindControl("SubOutcomeSelectionList");
            string theSubOutcome = selectedSubOutcome.SelectedValue;

            UNDPEntities db = new UNDPEntities();
            try
            {
                var subOutcome = (from data in db.sub_outcome_results
                                  where data.report_period_id == rprt
                                      && data.year_id == yr
                                      && data.project_id == proj
                                      && data.sub_outcome_id == theSubOutcome
                                  select data).FirstOrDefault();//FirstOrDefault() is important as it won't
                                                                //do a selection without it.
                if (subOutcome != null)
                {
                    string alert = "<script language='javascript' type='text/javascript'>alert('That Sub Outcome has already been given');</script>";
                    ScriptManager.RegisterClientScriptBlock(this,
                        GetType(),
                        "alert",
                        alert,
                        false);
                    e.Cancel = true;
                }
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }
//===============================================================================================================
        protected void SubOutcomeGridView_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                // loop all data rows
                foreach (DataControlFieldCell cell in e.Row.Cells)
                {
                    // check all cells in one row
                    foreach (Control control in cell.Controls)
                    {
                        // Must use LinkButton here instead of ImageButton
                        // if you are having Links (not images) as the command button.
                        Button button = control as Button;
                        if (button != null && button.CommandName == "Delete")
                            // Add delete confirmation
                            button.OnClientClick = "if (!confirm('Are you sure " +
                                   "you want to delete this record?')) return;";
                    }
                }
            }
        }*/
//===============================================================================================================
        protected void populateCpdOutputIndicator(string cpdID)
        {
            using (UNDPEntities db = new UNDPEntities())
            {
                try
                {
                    var cpd = (from c in db.cpd_output_indicators
                               where c.cpd_output_indicator_id == cpdID
                               select c.cpd_output_indicator_question).FirstOrDefault();

                    if (cpd == null)
                    {
                        //Important...Used at the Page_Init stage above
                        CDPOutputPane.FindControl("TextBox6");
                        TextBox6.Text = null;
                    }
                    else
                    {
                        //Important...Used at the Page_Init stage above
                        CDPOutputPane.FindControl("TextBox6");
                        TextBox6.Text = cpd;
                    }
                }
                catch (Exception ex)
                {
                    ErrorLabel.Text = "Database error : " + ex.Message + " : " + ex.StackTrace;
                    ErrorLabel.Visible = true;
                }
            }
        }
//===============================================================================================================
        protected void CpdOutputIndicatorList_SelectedIndexChanged(object sender, EventArgs e)
        {
            using(UNDPEntities db = new UNDPEntities())
            {
                try
                {
                    var cpd = (from c in db.cpd_output_indicators
                               where c.cpd_output_indicator_id == CpdOutputIndicatorList.SelectedValue
                               select c.cpd_output_indicator_question).FirstOrDefault();

                    if (cpd == null)
                    {
                        TextBox6.Text = null;
                    }
                    else
                    {
                        TextBox6.Text = cpd;
                    }
                }
                catch(Exception ex)
                {
                    ErrorLabel.Text = "Database error : " + ex.Message + " : " + ex.StackTrace;
                    ErrorLabel.Visible = true;
                }
            } 
        }
//===============================================================================================================
        protected void CpdGridView_DataBound(object sender, EventArgs e)
        {
            for (int i = 0; i <= CpdGridView.Rows.Count - 1; i++)
            {
                try
                {
                    Label statusLabel = (Label)CpdGridView.Rows[i].FindControl("StatusLabel");

                    if (statusLabel.Text == "Green")
                    {
                        CpdGridView.Rows[i].Cells[2].BackColor = Color.Green;
                    }
                    else if (statusLabel.Text == "Yellow")
                    {
                        CpdGridView.Rows[i].Cells[2].BackColor = Color.Yellow;
                    }
                    else if (statusLabel.Text == "Red")
                    {
                        CpdGridView.Rows[i].Cells[2].BackColor = Color.Red;
                    }
                }
                catch (Exception ex)
                {
                    return;
                }
            }
        }
//===============================================================================================================
        protected void NonCpdGridView_DataBound(object sender, EventArgs e)
        {
            for (int i = 0; i <= NonCpdGridView.Rows.Count - 1; i++)
            {
                try
                {
                    Label statusLabel = (Label)NonCpdGridView.Rows[i].FindControl("StatusLabel");

                    if (statusLabel.Text == "Green")
                    {
                        NonCpdGridView.Rows[i].Cells[3].BackColor = Color.Green;
                    }
                    else if (statusLabel.Text == "Yellow")
                    {
                        NonCpdGridView.Rows[i].Cells[3].BackColor = Color.Yellow;
                    }
                    else if (statusLabel.Text == "Red")
                    {
                        NonCpdGridView.Rows[i].Cells[3].BackColor = Color.Red;
                    }
                }
                catch (Exception ex)
                {
                    return;
                }
            }
        }
//===============================================================================================================
        protected void IPGridView_DataBound(object sender, EventArgs e)
        {
            for (int i = 0; i <= IPGridView.Rows.Count - 1; i++)
            {
                try
                {
                    Label statusLabel = (Label)IPGridView.Rows[i].FindControl("StatusLabel");

                    if (statusLabel.Text == "Green")
                    {
                        IPGridView.Rows[i].Cells[2].BackColor = Color.Green;
                    }
                    else if (statusLabel.Text == "Yellow")
                    {
                        IPGridView.Rows[i].Cells[2].BackColor = Color.Yellow;
                    }
                    else if (statusLabel.Text == "Red")
                    {
                        IPGridView.Rows[i].Cells[2].BackColor = Color.Red;
                    }
                }
                catch (Exception ex)
                {
                    return;
                }
            }
        }
//===============================================================================================================
        protected void CpdGridView_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                /*((Button)e.Row.Cells[6].Controls[0]).OnClientClick =
                    "if (!confirm('Do you really want to delete?')) return;";*/

                // loop all data rows
                foreach (DataControlFieldCell cell in e.Row.Cells)
                {
                    // check all cells in one row
                    foreach (Control control in cell.Controls)
                    {
                        // Must use LinkButton here instead of ImageButton
                        // if you are having Links (not images) as the command button.
                        Button button = control as Button;
                        if (button != null && button.CommandName == "Delete")
                            // Add delete confirmation
                            button.OnClientClick = "if (!confirm('Are you sure " +
                                   "you want to delete this record?')) return;";
                    }
                }
            }
        }
//===============================================================================================================
        protected void CpdGridView_RowUpdating(object sender, GridViewUpdateEventArgs e)
        {
            long proj = (long)Session["Project"];
            long rprt = (long)Session["ReportPeriod"];
            long yr = (long)Session["Year"];

            GridViewRow row = CpdGridView.Rows[e.RowIndex];

            DropDownList regList = (DropDownList)row.FindControl("DropDownList1");
            long reg = long.Parse(regList.SelectedValue);

            DropDownList cpdList = (DropDownList)row.FindControl("DropDownList2");
            string cpd_id = cpdList.SelectedValue;

            UNDPEntities db = new UNDPEntities();
            try
            {
                var cpd = (from result in db.cpd_output_results
                           where result.project_id == proj &&
                           result.year_id == yr &&
                           result.report_period_id == rprt &&
                           result.region_id == reg &&
                           result.cpd_output_indicator_id == cpd_id
                           select result).FirstOrDefault();//FirstOrDefault() is important as it won't
                                                            //do a selection without it.
                if (cpd != null)
                {
                    string alert = "<script language='javascript' type='text/javascript'>alert('That CPD output indicator has already been answered');</script>";
                    ScriptManager.RegisterClientScriptBlock(this,
                        GetType(),
                        "alert",
                        alert,
                        false);
                    e.Cancel = true;
                }
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }
//===============================================================================================================
        protected void clearCpdOutputSelectors()
        {
            CPDRegionList.SelectedIndex = 0;
            CpdOutputIndicatorList.SelectedIndex = 0;
            CpdStatusList.SelectedIndex = 0;
            CpdOutputResultTextBox.Text = null;
            CpdOutputCommentTextBox.Text = null;
        }
//===============================================================================================================
        protected void CPDOutputButton_Click(object sender, EventArgs e)
        {
            long proj = (long)Session["Project"];
            long rprt = (long)Session["ReportPeriod"];
            long yr = (long)Session["Year"];
            long reg = long.Parse(CPDRegionList.SelectedValue);
            string cpd_id = CpdOutputIndicatorList.SelectedValue;
            long status = long.Parse(CpdStatusList.SelectedValue);

            using (UNDPEntities db = new UNDPEntities())
            {
                try
                {
                    var cpd = (from result in db.cpd_output_results 
                                   where result.project_id == proj && 
                                   result.year_id == yr && 
                                   result.report_period_id == rprt && 
                                   result.region_id == reg && 
                                   result.cpd_output_indicator_id == cpd_id 
                                   select result).FirstOrDefault();//FirstOrDefault() is important as it won't
                                                                   //do a selection without it.

                    if(cpd == null)
                    {
                        //=========================================+
                        //  Add a new CPD_Output_Result Record     |
                        //=========================================+
                        cpd_output_results newCPD = new cpd_output_results();
                        newCPD.project_id = proj;
                        newCPD.year_id = yr;
                        newCPD.report_period_id = rprt;
                        newCPD.region_id = reg;
                        newCPD.cpd_output_indicator_id = cpd_id;
                        newCPD.indicator_status_id = status;
                        newCPD.result = CpdOutputResultTextBox.Text;
                        newCPD.comment = CpdOutputCommentTextBox.Text;
                        newCPD.submission_date = DateTime.Now.ToString();

                        db.cpd_output_results.AddObject(newCPD);
                        db.SaveChanges();
                    }
                    else if(cpd != null)
                    {
                        ClientScript.RegisterStartupScript(
                            this.GetType(),
                            "myalert",
                            "alert('That CPD output indicator has already been answered');",
                            true);
                        return;
                    }

                    //=============================+
                    //  Add a Log Track Record     |
                    //=============================+
                    log_track newTrack = db.log_track.SingleOrDefault(
                        lt => lt.project_id == proj &&
                        lt.year_id == yr &&
                        lt.report_period_id == rprt);
                    if (newTrack != null)
                    {
                        newTrack.log_track1 += DateTime.Now.ToString() + ": CPD Output Indicator added by :" + User.Identity.Name + ",";
                        db.SaveChanges();
                    }

                }
                catch (Exception ex)
                {
                    ErrorLabel.Text = "Error : " + ex.Message + " : " + ex.StackTrace;
                    ErrorLabel.Visible = true;
                }
            }
            clearCpdOutputSelectors();
            populateCpdOutputIndicator("1.1.1.1");
            CPDOutputUpdatePanel.FindControl("CpdGridView").DataBind();
        }
//===============================================================================================================
        protected void NonCpdGridView_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                /*((Button)e.Row.Cells[6].Controls[0]).OnClientClick =
                    "if (!confirm('Do you really want to delete?')) return;";*/

                // loop all data rows
                foreach (DataControlFieldCell cell in e.Row.Cells)
                {
                    // check all cells in one row
                    foreach (Control control in cell.Controls)
                    {
                        // Must use LinkButton here instead of ImageButton
                        // if you are having Links (not images) as the command button.
                        Button button = control as Button;
                        if (button != null && button.CommandName == "Delete")
                            // Add delete confirmation
                            button.OnClientClick = "if (!confirm('Are you sure " +
                                   "you want to delete this record?')) return;";
                    }
                }
            }
        }
//===============================================================================================================
        protected void clearNonCpdOutputSelectors()
        {
            NonCPDRegionList.SelectedIndex = 0;
            CpdOutputList.SelectedIndex = 0;
            NonCpdOutputQuestionTextBox.Text = null;
            NonCpdStatusList.SelectedIndex = 0;
            NonCpdOutputResultTextBox.Text = null;
            NonCpdOutputCommentTextBox.Text = null;
            CPDOutputTextBox.Text = null;
        }
//===============================================================================================================
        protected void populateCpdOutput(string cpdOutput)
        {
            using (UNDPEntities db = new UNDPEntities())
            {
                try
                {
                    var cpd_o = (from co in db.cpd_outputs where 
                                     co.cpd_output_id == cpdOutput 
                                     select co.cpd_output).FirstOrDefault();

                    if (cpd_o == null)
                    {
                        //Important...Used at the Page_Init stage above
                        NonCPDOutputPane.FindControl("CPDOutputTextBox");
                        CPDOutputTextBox.Text = null;
                    }
                    else
                    {
                        //Important...Used at the Page_Init stage above
                        NonCPDOutputPane.FindControl("CPDOutputTextBox");
                        CPDOutputTextBox.Text = cpd_o;
                    }
                }
                catch (Exception ex)
                {
                    ErrorLabel.Text = "Database error : " + ex.Message + " : " + ex.StackTrace;
                    ErrorLabel.Visible = true;
                }
            }
        }
//===============================================================================================================
        protected void CpdOutputList_SelectedIndexChanged(object sender, EventArgs e)
        {
            using (UNDPEntities db = new UNDPEntities())
            {
                try
                {
                    var cpd_o = (from co in db.cpd_outputs where 
                                     co.cpd_output_id == CpdOutputList.SelectedValue 
                                     select co.cpd_output).FirstOrDefault();

                    if (cpd_o == null)
                    {
                        CPDOutputTextBox.Text = null;
                    }
                    else
                    {
                        CPDOutputTextBox.Text = cpd_o;
                    }
                }
                catch (Exception ex)
                {
                    ErrorLabel.Text = "Database error : " + ex.Message + " : " + ex.StackTrace;
                    ErrorLabel.Visible = true;
                }
            }
        }
//===============================================================================================================
        protected void NonCpdOutputButton_Click(object sender, EventArgs e)
        {
            long proj = (long)Session["Project"];
            long rprt = (long)Session["ReportPeriod"];
            long yr = (long)Session["Year"];
            long reg = long.Parse(NonCPDRegionList.SelectedValue);
            string cpd = CpdOutputList.SelectedValue;
            long status = long.Parse(NonCpdStatusList.SelectedValue);

            using (UNDPEntities db = new UNDPEntities())
            {
                try
                {
                    //=============================================+
                    //  Add a new NON_CPD_Output_Result Record     |
                    //=============================================+
                    non_cpd_output_indicators newNonCPD = new non_cpd_output_indicators();
                    newNonCPD.project_id = proj;
                    newNonCPD.year_id = yr;
                    newNonCPD.report_period_id = rprt;
                    newNonCPD.region_id = reg;
                    if (CpdOutputList.SelectedValue != "")
                    {
                        newNonCPD.cpd_output_id = cpd;
                    }
                    newNonCPD.non_cpd_outp_indicator_question = NonCpdOutputQuestionTextBox.Text;
                    newNonCPD.indicator_status_id = status;
                    newNonCPD.result = NonCpdOutputResultTextBox.Text;
                    newNonCPD.comment = NonCpdOutputCommentTextBox.Text;
                    newNonCPD.submission_date = DateTime.Now.ToString();

                    db.non_cpd_output_indicators.AddObject(newNonCPD);
                    db.SaveChanges();

                    //=============================+
                    //  Add a Log Track Record     |
                    //=============================+
                    log_track newTrack = db.log_track.SingleOrDefault(
                        lt => lt.project_id == proj &&
                        lt.year_id == yr &&
                        lt.report_period_id == rprt);
                    if (newTrack != null)
                    {
                        newTrack.log_track1 += DateTime.Now.ToString() + ": Non CPD Output Indicator added by :" + User.Identity.Name + ",";
                        db.SaveChanges();
                    }

                }
                catch (Exception ex)
                {
                    ErrorLabel.Text = "Error : " + ex.Message + " : " + ex.StackTrace;
                    ErrorLabel.Visible = true;
                }
            }
            clearNonCpdOutputSelectors();
            NonCpdOutputUpdatePanel.FindControl("NonCpdGridView").DataBind();
        }
//===============================================================================================================
        protected void IPGridView_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                /*((Button)e.Row.Cells[6].Controls[0]).OnClientClick =
                    "if (!confirm('Do you really want to delete?')) return;";*/

                // loop all data rows
                foreach (DataControlFieldCell cell in e.Row.Cells)
                {
                    // check all cells in one row
                    foreach (Control control in cell.Controls)
                    {
                        // Must use LinkButton here instead of ImageButton
                        // if you are having Links (not images) as the command button.
                        Button button = control as Button;
                        if (button != null && button.CommandName == "Delete")
                            // Add delete confirmation
                            button.OnClientClick = "if (!confirm('Are you sure " +
                                   "you want to delete this record?')) return;";
                    }
                }
            }
        }
//===============================================================================================================
        protected void clearInternalProcessIndicators()
        {
            IPRegionList.SelectedIndex = 0;
            InternalProcessQuestionTextBox.Text = null;
            IPStatusList.SelectedIndex = 0;
            InternalProcessResultTextBox.Text = null;
            InternalProcessCommentTextBox.Text = null;
        }
//===============================================================================================================
        protected void InternalProcessButton_Click(object sender, EventArgs e)
        {
            long proj = (long)Session["Project"];
            long rprt = (long)Session["ReportPeriod"];
            long yr = (long)Session["Year"];
            long reg = long.Parse(IPRegionList.SelectedValue);
            long status = long.Parse(IPStatusList.SelectedValue);

            using (UNDPEntities db = new UNDPEntities())
            {
                try
                {
                    //=============================================+
                    //  Add a new NON_CPD_Output_Result Record     |
                    //=============================================+
                    internal_process_indicators ipIndicator = new internal_process_indicators();
                    ipIndicator.project_id = proj;
                    ipIndicator.year_id = yr;
                    ipIndicator.report_period_id = rprt;
                    ipIndicator.region_id = reg;
                    ipIndicator.internal_process_question = InternalProcessQuestionTextBox.Text;
                    ipIndicator.indicator_status_id = status;
                    ipIndicator.result = InternalProcessResultTextBox.Text;
                    ipIndicator.comment = InternalProcessCommentTextBox.Text;
                    ipIndicator.submission_date = DateTime.Now.ToString();

                    db.internal_process_indicators.AddObject(ipIndicator);
                    db.SaveChanges();

                    //=============================+
                    //  Add a Log Track Record     |
                    //=============================+
                    log_track newTrack = db.log_track.SingleOrDefault(
                        lt => lt.project_id == proj &&
                        lt.year_id == yr &&
                        lt.report_period_id == rprt);
                    if (newTrack != null)
                    {
                        newTrack.log_track1 += DateTime.Now.ToString() + ": Internal Process indicator by :" + User.Identity.Name + ",";
                        db.SaveChanges();
                    }

                }
                catch (Exception ex)
                {
                    ErrorLabel.Text = "Error : " + ex.Message + " : " + ex.StackTrace;
                    ErrorLabel.Visible = true;
                }
            }
            clearInternalProcessIndicators();
            InternalUpdatePanel.FindControl("IPGridView").DataBind();
        }
//===============================================================================================================
        protected void populateCFS(long pcproj, long pcrprt, long pcyr)
        {
            using (UNDPEntities db = new UNDPEntities())
            {
                try
                {
                    var cfs = (from pr in db.project_reports 
                                   where pr.project_id == pcproj && 
                                   pr.year_id == pcyr && 
                                   pr.report_period_id == pcrprt 
                                   select pr).FirstOrDefault();

                    FinancialSummaryPane.FindControl("ApprovedBudgetTextBox");
                    FinancialSummaryPane.FindControl("TotalTextBox");
                    FinancialSummaryPane.FindControl("BalanceTextBox");
                    FinancialSummaryPane.FindControl("DeliveryTextBox");

                    ApprovedBudgetTextBox.Text = cfs.approved_budget_cfs;
                    TotalTextBox.Text = cfs.total_cfs;
                    BalanceTextBox.Text = cfs.balance_cfs;
                    DeliveryTextBox.Text = cfs.delivery_cfs;
                }
                catch (Exception ex)
                {
                    ErrorLabel.Text = "Database error : " + ex.Message + " : " + ex.StackTrace;
                    ErrorLabel.Visible = true;
                }
            }
        }
//===============================================================================================================
        protected void CFSButton_Click(object sender, EventArgs e)
        {
            long proj = (long)Session["Project"];
            long rprt = (long)Session["ReportPeriod"];
            long yr = (long)Session["Year"];
            try
            {
                UNDPEntities db = new UNDPEntities();
                project_reports cfs = db.project_reports.SingleOrDefault(
                                        pr => pr.project_id == proj && 
                                        pr.report_period_id == rprt && 
                                        pr.year_id == yr);

                if (cfs != null)
                {
                    cfs.approved_budget_cfs = ApprovedBudgetTextBox.Text;
                    cfs.total_cfs = TotalTextBox.Text;
                    cfs.balance_cfs = BalanceTextBox.Text;
                    cfs.delivery_cfs = DeliveryTextBox.Text;
                    db.SaveChanges();
                }
                else if (cfs == null)
                {
                    Response.Redirect("~/Project/Saved_Projects/");
                }

                //=============================+
                //  Add a Log Track Record     |
                //=============================+
                log_track newTrack = db.log_track.SingleOrDefault(
                    lt => lt.project_id == proj &&
                    lt.year_id == yr &&
                    lt.report_period_id == rprt);
                if (newTrack != null)
                {
                    newTrack.log_track1 += DateTime.Now.ToString() + ": Cummulative Financial Summary modified by :" + User.Identity.Name + ",";
                    db.SaveChanges();
                }

            }
            catch (Exception ex)
            {
                ErrorLabel.Text = "Database error : " + ex.Message + " : " + ex.StackTrace;
                ErrorLabel.Visible = true;
            }
            populateCFS(proj, rprt, yr);
        }
//===============================================================================================================
        protected void populateProjectCommentTextbox(long CProj, long CRprt, long CYr)
        {
            using (UNDPEntities db = new UNDPEntities())
            {
                try
                {
                    project_reports pr = db.project_reports.SingleOrDefault(
                                            myPr => myPr.project_id == CProj &&
                                            myPr.year_id == CYr &&
                                            myPr.report_period_id == CRprt);

                    ProjectCommentTextBox.Text = pr.comment;
                }
                catch (Exception ex)
                {
                    ErrorLabel.Text = "Error : " + ex.Message + " : " + ex.StackTrace;
                    ErrorLabel.Visible = true;
                }
            }
        }
//===============================================================================================================
        protected void ProjectCommentButton_Click(object sender, EventArgs e)
        {
            long proj = (long)Session["Project"];
            long rprt = (long)Session["ReportPeriod"];
            long yr = (long)Session["Year"];

            using (UNDPEntities db = new UNDPEntities())
            {
                try
                {
                    //===================================================+
                    //  UPDATE the comment Record in project_reports     |
                    //===================================================+
                    project_reports pr = db.project_reports.SingleOrDefault(
                                            myPr => myPr.project_id == proj && 
                                            myPr.year_id == yr && 
                                            myPr.report_period_id == rprt);

                    pr.comment = ProjectCommentTextBox.Text;
                    db.SaveChanges();

                    //=============================+
                    //  Add a Log Track Record     |
                    //=============================+
                    log_track newTrack = db.log_track.SingleOrDefault(
                        lt => lt.project_id == proj &&
                        lt.year_id == yr &&
                        lt.report_period_id == rprt);
                    if (newTrack != null)
                    {
                        newTrack.log_track1 += DateTime.Now.ToString() + ": Project Comment added by :" + User.Identity.Name + ",";
                        db.SaveChanges();
                    }

                }
                catch (Exception ex)
                {
                    ErrorLabel.Text = "Error : " + ex.Message + " : " + ex.StackTrace;
                    ErrorLabel.Visible = true;
                }
            }
            populateProjectCommentTextbox(proj, rprt, yr);
        }
//===============================================================================================================
        protected void PopulateAcronyms(long proj)
        {
            using (UNDPEntities db = new UNDPEntities())
            {
                try
                {

                    var acronymsList = (from data in db.acronym_list
                               where data.project_id == proj select data).FirstOrDefault();

                    AcronymsPane.FindControl("AcronymsTxbx");

                    if (acronymsList != null)
                    {
                        AcronymsTxbx.Text = acronymsList.acronyms;
                    }
                }
                catch (Exception ex)
                {
                    ErrorLabel.Text = "Error : " + ex.Message + " : " + ex.StackTrace;
                    ErrorLabel.Visible = true;
                }
            }
        }
//===============================================================================================================
        protected void AcronymBtn_Click(object sender, EventArgs e)
        {
            long proj = (long)Session["Project"];

            using (UNDPEntities db = new UNDPEntities())
            {
                try
                {
                    if (Session["Project"] == null)
                    {
                        Response.Redirect("~/Project/Saved_Projects/", true);
                    }
                    acronym_list newAcronyms = db.acronym_list.FirstOrDefault(
                                        data => data.project_id == proj);
                    if (newAcronyms != null)
                    {
                        newAcronyms.acronyms = AcronymsTxbx.Text;
                        db.SaveChanges();
                    }
                    else
                    {
                        acronym_list newAcronymList = new acronym_list();
                        newAcronymList.project_id = proj;
                        newAcronymList.acronyms = AcronymsTxbx.Text;
                        db.acronym_list.AddObject(newAcronymList);
                        db.SaveChanges();
                    }
                }
                catch (Exception ex)
                {
                    ErrorLabel.Text = "Error : " + ex.Message + " : " + ex.StackTrace;
                    ErrorLabel.Visible = true;
                }
            }
            PopulateAcronyms(proj);
        }
//===============================================================================================================
        protected void SubmitReportButton_Click(object sender, EventArgs e)
        {
            long proj = (long)Session["Project"];
            long rprt = (long)Session["ReportPeriod"];
            long yr = (long)Session["Year"];
            /*
             * Put saved == false and put submitted == true
             */

            using (UNDPEntities db = new UNDPEntities())
            {

//======================TO DELETE================================================================
                //char[] separator = new char[] { '\\' };
                //string[] uName = User.Identity.Name.Split(separator);
                //string uname2 = uName[1] + "@undp.org";
                //bool checkIfProjectMgr = (bool)db.users.FirstOrDefault(u => 
                //                        u.user_email == uname2).is_project_manager;
//=====================TO DELETE=============================================================

                string chkUEmail = User.Identity.Name.ToString();
                bool checkIfProjectMgr = (bool)db.users.FirstOrDefault(u =>
                                        u.user_email == chkUEmail).is_project_manager;

                if (!User.IsInRole("Administrator"))
                {
                    if (!checkIfProjectMgr)
                    {
                        WarningLabel.Text = "Only Your Project Manager can submit this report.";
                        WarningLabel.Visible = true;
                        SubmitReportButton.Visible = false;
                        return;
                    }
                }


                try
                {
                    project_reports pr = db.project_reports.SingleOrDefault(
                                            myPr => myPr.project_id == proj && 
                                            myPr.year_id == yr && 
                                            myPr.report_period_id == rprt);

                    pr.project_editor = AuthorTextBox.Text;
                    pr.saved = false;
                    pr.submitted = true;
                    pr.submission_date = DateTime.Now.ToString();

                    db.SaveChanges();
                    //Just to make the code full proof
                    AuthorTextBox.Text = AuthorTextBox.Text;

                    //=============================================+
                    //  Send Email Message to Programme People     |
                    //=============================================+

                    //Create the mail message
                    MailMessage mail = new MailMessage();

                    //Set the addresses and specify a friendly 'from' name
                    mail.From = new MailAddress("monitoring.so@undp.org", "M&E");
                    const string fromPassword = "Monitoring2012";

                    //Add multiple addresses
                    long prog_id = db.projects.Single(
                                    id => id.project_id == proj).program_id;
                    var prog_email = (from p in db.users where p.program_id == prog_id && 
                                        p.active == true select p.user_email);
                    foreach (var emailAdd in prog_email)
                    {
                        mail.To.Add(emailAdd.ToString());
                    }

                    //Set the content
                    mail.Subject = "Monitoring and Evaluation: Reporting System";

                    System.Text.StringBuilder sbuilder = new System.Text.StringBuilder();
                    sbuilder.Append("Dear programme team,").AppendLine().AppendLine();
                    sbuilder.Append("Please note that the ");
                    sbuilder.Append(pr.project.project1.Trim() + " " +
                        pr.report_period.report_period1.Trim() + " " + pr.year.year1.Trim());
                    sbuilder.Append(" quarterly report has been submitted to you for review.").AppendLine().AppendLine();

                    if (ProjectCommentTextBox.Text != string.Empty)
                    {
                        sbuilder.Append("Project comments include: ");
                        sbuilder.Append(ProjectCommentTextBox.Text).AppendLine().AppendLine();
                    }

                    sbuilder.Append("You can access the system here: http://www.ppu-reporting.net:8083/ ").AppendLine().AppendLine();
                    sbuilder.Append("Thank you").AppendLine().AppendLine();
                    sbuilder.Append("M&E team").AppendLine().AppendLine().AppendLine();
                    sbuilder.Append("*This email is automatically generated - please do not reply").AppendLine();

                    mail.Body = sbuilder.ToString();

                    //Send the message
                    var smtp = new SmtpClient
                    {
                        Host = "193.194.138.69",
                        Port = 25,
                        EnableSsl = true,
                        DeliveryMethod = SmtpDeliveryMethod.Network,
                        UseDefaultCredentials = false,
                        Credentials = new NetworkCredential(mail.From.Address, fromPassword)
                    };

                    ServicePointManager.ServerCertificateValidationCallback = delegate(
                            object s, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
                    { return true; };
                    try
                    {
                        smtp.Send(mail);
                    }
                    catch (Exception ex)
                    {
                        ErrorLabel.Text = "MSG NOT SENT " + ex.Message + " " + ex.StackTrace;
                    }

                    //=============================================+
                    //                  END SEND MAIL              |
                    //=============================================+

                    //=============================+
                    //  Add a Log Track Record     |
                    //=============================+
                    log_track newTrack = db.log_track.SingleOrDefault(
                        lt => lt.project_id == proj &&
                        lt.year_id == yr &&
                        lt.report_period_id == rprt);
                    if (newTrack != null)
                    {
                        newTrack.log_track1 += DateTime.Now.ToString() + ": Project Submitted by :" + User.Identity.Name + ",";
                        db.SaveChanges();
                    }

                    Session["Project"] = null;
                    Session["ReportPeriod"] = null;
                    Session["Year"] = null;

                    Response.Redirect("~/Project/Saved_Projects/");
                }
                catch (Exception ex)
                {
                    ErrorLabel.Text = "Error : " + ex.Message + " : " + ex.StackTrace;
                    ErrorLabel.Visible = true;
                    //Foolproofing the code
                    AuthorTextBox.Text = AuthorTextBox.Text;
                }
            }
            Session["Project"] = null;
            Session["ReportPeriod"] = null;
            Session["Year"] = null;
        }
    }
}